package br.com.documentos.model.vo;

import java.util.Collection;
import java.util.Collections;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import br.com.documentos.model.entity.Usuario;
import br.com.documentos.model.exceptions.DocumentosOnlineException;

public class UsuarioAuthentication implements UserDetails{

	private static final long serialVersionUID = 1L;

	private Usuario usuario;
	
	@SuppressWarnings("serial")
	public static final GrantedAuthority ROLE_ADMIN = new GrantedAuthority() {
		public String getAuthority() {
			return "ROLE_ADMIN";
		}
	};

	public static Usuario getUsuarioLogado(){
		UsuarioAuthentication usuarioAuthentication = (UsuarioAuthentication) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		
		if( usuarioAuthentication != null && usuarioAuthentication.getUsuario() != null ){
			return usuarioAuthentication.getUsuario();
		}
		else {
			throw new DocumentosOnlineException("Sessão inválida.");
		}
	}
	
	public Usuario getUsuario(){
		return usuario;
	}
	
	public UsuarioAuthentication( Usuario usuario ){
		this.usuario = usuario;
	}
	
	public Collection<GrantedAuthority> getAuthorities() {
		return Collections.singletonList(ROLE_ADMIN);
	}

	public String getPassword() {
		return usuario.getSenha();
	}

	public String getUsername() {
		return usuario.getEmail();
	}

	public boolean isAccountNonExpired() {
		return true;
	}

	public boolean isAccountNonLocked() {
		return true;
	}

	public boolean isCredentialsNonExpired() {
		return true;
	}

	public boolean isEnabled() {
		return true;
	}

}
